<template>
  <div class="dialog">
    <el-dialog :title="'直鱼管理' + titleText" :visible.sync="showDialog" width="55%" top="0" :close-on-click-modal="false"
      @close="cancel">
      <el-form ref="ruleForm" label-position="left" :model="formData" :rules="rules" class="el-form">
        <el-form-item label="鱼塘名称: " prop="fishPondId" class="w50p">
          <el-select filterable clearable v-model="formData.fishPondId" placeholder="请选择" filterable clearable @change="pondChange">
            <el-option v-for="(item, index) in pondList" :label="item.pondName" :value="item.fishPondId"
              :key="index + 'diseaseBank'" />
          </el-select>
        </el-form-item>
        <el-form-item label="批次编号: " prop="productionBatchId" class="w50p">
          <el-select filterable clearable v-model="formData.productionBatchId" placeholder="请先选择鱼塘" filterable clearable @change="batchChange">
            <el-option v-for="(item, index) in batchList"
              :label="`${item.mnecode}_${item.varietyName}`" :disabled="!item.num"
              :value="item.productionBatchId" :key="index + 'diseaseBank'" />
          </el-select>
        </el-form-item>
        <el-form-item label="直鱼数量:" class="w50p" prop="num">
          <el-input v-model="formData.num" type="number" clearable placeholder="请输入直鱼数量">
            <template slot="append">尾</template>
          </el-input>
        </el-form-item>
        <el-form-item label="直鱼重量:" type="number" class="w50p" prop="weight">
          <el-input v-model="formData.weight" clearable placeholder="请输入直鱼重量">
            <template slot="append">斤</template>
          </el-input>
        </el-form-item>
        <el-form-item label="处理人:" prop="staffId" class="w50p">
          <el-select filterable clearable disabled v-model="formData.staffName" placeholder="请选择" filterable clearable @change="staffChange">
            <el-option v-for="(item, index) in staffList" :label="item.staffName" :value="item.staffName"
              :key="index + 'staff'" />
          </el-select>
        </el-form-item>
        <el-form-item label="发现日期:" class="w50p" prop="deadDate">
          <el-date-picker v-model="formData.deadDate" type="date" placeholder="选择日期" value-format="yyyy-MM-dd" clearable
            :picker-options="pickerOptions" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button class="cancelbtn" @click="cancel()">取 消</el-button>
        <el-button type="primary" class="savebtn" @click="save('ruleForm')">保 存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import AbnormalDeathmanagementApi from "@/api/health-management/abnormal-death-management";
import BatchMangeApi from "@/api/batch-mange";
import StaffApi from "@/api/basic-info-manage/staff";
import FishPondApi from "@/api/basic-info-manage/fishPond";
import { dialogMixin } from "@/utils/dialogMixin"
let maxTime = null
let minTime = new Date();
export default {
  name: '',
  components: {},
  mixins: [dialogMixin],
  props: {
    // 弹框名称
    titleText: {
      type: String,
      default: ""
    },
    nowChanceStau: {
      type: String,
      default: ""
    },
    show: {
      type: Boolean,
      default: false
    },
    editObject: {
      type: [Object],
      default: () => {
        return {}
      }
    },
  },
  data () {
    let checkInt = (rule, value, callback) => {
      if (value) {
        if (Number(value) && value > 0) {
          callback();
        } else {
          callback(new Error('不能为负数'));
        }
      } else {
        callback(new Error(rule.emptyMsg));
      }
    };
    return {
      pickerOptions: {
        disabledDate (time) {
          return time.getTime() < new Date(new Date(maxTime).getTime(new Date(maxTime))) || time.getTime() > new Date().getTime();
        },

        shortcuts: [{
          text: '今天',
          onClick (picker) {
            picker.$emit('pick', new Date());
          }
        }, {
          text: '昨天',
          onClick (picker) {
            const date = new Date();
            date.setTime(date.getTime() - 3600 * 1000 * 24);
            if (maxTime < date.getTime() - 3600 * 1000 * 24) {
              picker.$emit('pick', date);
            } else {
              picker.$emit('pick', maxTime);
            }
          }
        }, {
          text: '一周前',
          onClick (picker) {
            const date = new Date();
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
            if (maxTime < date.getTime() - 3600 * 1000 * 24 * 7) {
              picker.$emit('pick', date);
            } else {
              picker.$emit('pick', maxTime);
            }
          }
        }],
      },
      formData: {},
      rules: {
        fishPondId: [
          { required: true, message: "请选择鱼塘", trigger: ["change", "blur"] }
        ],
        productionBatchId: [
          { required: true, message: "请选择批次", trigger: ["change", "blur"] }
        ],
        num: [
          { required: true, emptyMsg: "请输入直鱼数量", trigger: ["change", "blur"], validator: checkInt }
        ],
        weight: [
          { required: true, emptyMsg: "请输入直鱼重量", trigger: ["change", "blur"], validator: checkInt }
        ],
        staffId: [
          { required: true, message: "请选择处理人", trigger: ["change", "blur"] }
        ],
        deadDate: [
          { required: true, message: "请选择日期", trigger: ["change", "blur"] }
        ],
      },
      diseaseBankList: [],
      staffList: [],
      batchList: [],
      pondList: [],
      showDialog: this.show
    };
  },

  watch: {
    show (v) {
      this.showDialog = v;
    },
    nowChanceStau (v) {
      if (v === 'add') {
        let staffName = sessionStorage.getItem("staffName")
        let staffId = sessionStorage.getItem("staffId")
        this.formData = {
          productionBatchId: '',
          deadDate: this.getNowTime()
        }
        let userList = this.staffList.filter(item => {
          return Number(item.staffId) === Number(staffId)
        })
        this.formData = {
          staffName: userList.length == 0 ? this.staffList[0].staffName : staffName,
          staffId: userList.length == 0 ? this.staffList[0].staffId : Number(staffId),
        }
        this.$set(this.formData, 'productionBatchId', '')
        this.$set(this.formData, 'deadDate', this.formatDateTimeMHS(new Date()))
        // if (this.formData.staffId == 1) {
        //   this.formData.staffName = this.staffList[0].staffName
        //   this.formData.staffId = this.staffList[0].staffId
        // }
        this.$nextTick(() => {
          this.$refs['ruleForm'].clearValidate()
        })
      }
      if (v === 'edit') {
        this.formData = this.editObject
        if (this.formData.fishPondId) {
          this.pondChange(this.formData.fishPondId, 'edit')
        }
      }
    }
  },
  created () {
    maxTime = null
  },
  mounted () {
    this.queryStaff()
    this.queryPond()
    // this.queryBatch()
  },
  methods: {
    batchChange (e) {
      maxTime = ''
      this.formData.deadDate = new Date()
      this.batchList.find(item => {
        if (item.productionBatchId === e) {
          maxTime = new Date(item.buildDateTime)
          // this.formData.deadDate = this.formatDateTimeMHS(maxTime)
        }
      })
    },
    queryPond () {
      FishPondApi.queryByCondition().then(res => {
        this.pondList = res.data
      })
    },
    queryBatch () {
      BatchMangeApi.queryByCondition({ status: 'UN_COMPLETE' }).then(res => {
        this.batchList = res.data
      })
    },
    queryStaff () {
      StaffApi.queryByCondition().then(res => {
        this.staffList = res.data
      })
    },
    staffChange (e) {
      this.staffList.find((item) => {
        if (item.staffId === e) {
          this.formData.staffName = item.staffName
          return true
        }
      })
    },
    pondChange (e, type) {
      BatchMangeApi.queryBatchByPondIdUnComplete({ pondId: e }).then(res => {
        this.batchList = res.data
        type !== 'edit' && (this.formData.productionBatchId = '')
      })
    },
    save (formData) {
      this.$refs[formData].validate(valid => {
        if (valid) {
          if (this.nowChanceStau === "edit") {
            AbnormalDeathmanagementApi.edit(this.formData).then(res => {
              if (res.success) {
                this.$message.success("修改成功！");
                this.close()
              } else if (res.success === false && res.errCode === 200) {
                this.$message.error(res.message);
              } else {
                this.$message.error("系统错误,请稍后再试");
              }
            });
          } else if (this.nowChanceStau === "add") {
            AbnormalDeathmanagementApi.add(this.formData).then(res => {
              if (res.success) {
                this.$message.success("添加成功");
                this.close()
              } else if (res.errCode === 200) {
                this.$message.error(res.message);
              } else {
                this.$message.error("系统错误,请稍后再试");
              }
            });
          }
        } else {
          return false;
        }
      });
    },
    close () {
      this.$emit("closeDialog");
    },
    cancel () {
      this.$emit("cancelDialog");
    }
  }
};
</script>

<style lang="scss" scoped></style>
